/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import DTO.Users;
import DTO.User;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import util.DBUtil;

/**
 *
 * @author ThanhTai
 */
public class UserDAO {

    DBUtil util;

    public Users getAllUser(String condition) throws SQLException, Exception {
        List<User> userList = new ArrayList<User>();
        ResultSet rs = null;
        Connection conn = null;
        Statement stm = null;
        StringBuilder strBuilder = new StringBuilder();
        util = new DBUtil();
        User user;

        try {
            Class.forName(util.getDriverName());
            DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
            conn = DriverManager.getConnection(util.getURL(), util.getUsername(), util.getPassword());
            strBuilder.append("SELECT * FROM Users");
            if (condition != null && !condition.equals("")) {
                strBuilder.append(condition);
            }
            stm = conn.createStatement();
            rs = stm.executeQuery(strBuilder.toString());
            userList = new ArrayList<User>();
            while (rs.next()) {
                user = new User(rs.getString("username"), "*****",//rs.getString("password"),
                        rs.getString("fullName"), rs.getString("userRole"));
                userList.add(user);
            }
            return new Users(userList);
        } catch (SQLException e) {
            throw (e);
        } catch (Exception e) {
            throw (e);
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                throw (e);
            }
            try {
                stm.close();
            } catch (SQLException e) {
                throw (e);
            }
            try {
                conn.close();
            } catch (SQLException e) {
                throw (e);
            }
        }
    }
}
